package top.lshaci.learning.springboot.web.config;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.lshaci.learning.springboot.web.annotation.LoginUser;
import top.lshaci.learning.springboot.web.model.LoginUserBo;

import javax.servlet.http.HttpSession;

/**
 * LoginUserMethodArgumentResolver
 *
 * @author lshaci
 * @since 1.0.0
 */
public class LoginUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(LoginUserBo.class) &&
                parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 1、通过token获取用户ID, 然后到数据库中查询用户信息
        String token = webRequest.getHeader("token");
        // 2、从session中获取用户信息
        ServletWebRequest request = (ServletWebRequest) webRequest;
        HttpSession session = request.getRequest().getSession();
        Object sessionUser = session.getAttribute("LoginUser");

        LoginUserBo loginUser = new LoginUserBo();
        loginUser.setId(1L);
        loginUser.setUsername("管理员");
        return loginUser;
    }
}
